/*
 * @Author: 段本显
 * @Desc: 文件简介
 * @Date: 2021-08-06 11:40:34
 * @LastEditors: 段本显
 * @LastEditTime: 2021-09-24 15:17:26
 * @Email: duanbenxian@jianq.com
 * @Mark: 如果有bug，那肯定不是我的锅，噜噜噜
 */
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import'
import path from 'path'
import externalGlobals from 'rollup-plugin-external-globals'
import Spritesmith from 'vite-plugin-spritesmith'
import ViteRestart from 'vite-plugin-restart'
import { minifyHtml, injectHtml } from 'vite-plugin-html'
import { configMockPlugin } from './mock.config'
import viteCompression from 'vite-plugin-compression'
import { VitePWA } from 'vite-plugin-pwa'
import mkcert from 'vite-plugin-mkcert'
// https://vitejs.dev/config/
export default ({ mode }) => {
  const isBuild = mode === 'production'
  // const base = isBuild ? '/emm-register/' : '/'
  const base = '/'
  const cdn = {
    css: [
      'https://cdn.jsdelivr.net/npm/element-plus@1.1.0-beta.12/theme-chalk/index.css'
    ],
    js: isBuild
      ? [
          'https://cdn.jsdelivr.net/npm/vue@3.2.0/dist/vue.global.min.js',
          'https://cdn.jsdelivr.net/npm/vue-router@4.0.0/dist/vue-router.global.min.js',
          'https://cdn.jsdelivr.net/npm/vuex@4.0.2/dist/vuex.global.min.js',
          'https://cdn.jsdelivr.net/npm/axios@0.18.0/dist/axios.min.js',
          'https://cdn.jsdelivr.net/npm/element-plus@1.1.0-beta.12/dist/index.full.js',
          'https://cdn.jsdelivr.net/npm/mockjs@1.1.0/dist/mock.min.js',
          'https://cdn.jsdelivr.net/npm/vue-i18n@9.1.7/dist/vue-i18n.global.min.js'
        ]
      : []
  }
  const alias = {
    '@': path.resolve(__dirname, 'src'),
    '@components': path.resolve(__dirname, './src/components/'),
    '@assets': path.resolve(__dirname, 'src/assets'),
    '@views': path.resolve(__dirname, 'src/views'),
    '@axios': path.resolve(__dirname, 'src/axios'),
    '@lang': path.resolve(__dirname, './src/lang'),
    '@router': path.resolve(__dirname, './src/router'),
    '@store': path.resolve(__dirname, './src/store'),
    '@api': path.resolve(__dirname, './src/axios/api')
  }
  if (!isBuild) {
    // 解决警告You are running the esm-bundler build of vue-i18n.
    alias['vue-i18n'] = 'vue-i18n/dist/vue-i18n.cjs.js'
  }
  return defineConfig({
    base,
    plugins: [
      ViteRestart({
        restart: ['vite.config.[jt]s']
      }),
      mkcert({
        source: 'coding'
      }),
      viteCompression({
        threshold: 1024 * 30
      }),
      configMockPlugin(isBuild),
      Spritesmith({
        watch: true,
        src: {
          cwd: './src/assets/sprites',
          glob: '*.png'
        },
        target: {
          image: './src/assets/sprite.png',
          css: [
            './src/assets/sprite.css',
            [
              './src/assets/sprite.json',
              {
                format: 'json_texture'
              }
            ]
          ]
        },
        apiOptions: {
          cssImageRef: './sprite.png'
        }
      }),
      vue(),
      styleImport({
        libs: [
          {
            libraryName: 'element-plus',
            esModule: true,
            ensureStyleFile: true,
            resolveStyle: (name) => {
              return `element-plus/lib/theme-chalk/${name}.css`
            },
            resolveComponent: (name) => {
              return `element-plus/lib/${name}`
            }
          }
        ]
      }),
      minifyHtml(),
      injectHtml({
        data: {
          title: 'appiron',
          // injectScript: '<script src="./inject.js"></script>',
          cdn: {
            js: [],
            css: []
          }
        }
      }),
      VitePWA({
        base,
        registerType: 'autoUpdate',
        workbox: {
          skipWaiting: true,
          clientsClaim: true,
          globDirectory: 'dist/',
          globPatterns: ['**/**'],
          runtimeCaching: [
            {
              urlPattern: /^https:\/\/(rest|web)api\.amap\.com/,
              handler: 'NetworkFirst',
              options: {
                networkTimeoutSeconds: 1,
                cacheName: 'amap-cache',
                cacheableResponse: {
                  statuses: [0, 200]
                }
              }
            }
          ]
        }
      })
    ],
    css: {
      preprocessorOptions: {
        scss: {
          // 注意：键名是scss不是sass！
          // 这里写你想导入全局scss变量的路径
          additionalData: `@import "@assets/scss/reset.scss";@import "@assets/scss/variable.scss";`
        }
      }
    },
    resolve: {
      alias
    },
    build: {
      assetsDir: 'static',
      brotliSize: false,
      assetsInlineLimit: 0,
      rollupOptions: {
        output: {
          chunkFileNames: `static/js/[name]-[hash].js`,
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
          // manualChunks(id) {
          //   if (id.includes('node_modules')) {
          //     return id
          //       .toString()
          //       .split('node_modules/')[1]
          //       .split('/')[0]
          //       .toString()
          //   }
          // }
        }
        // external: [
        //   'vue',
        //   'vue-router',
        //   'vuex',
        //   'axios',
        //   'element-plus',
        //   'mockjs',
        //   'vue-i18n'
        // ],
        // plugins: [
        //   externalGlobals({
        //     vue: 'Vue',
        //     'vue-router': 'VueRouter',
        //     vuex: 'Vuex',
        //     axios: 'axios',
        //     'element-plus': 'ElementPlus',
        //     mockjs: 'Mock',
        //     'vue-i18n': 'VueI18n'
        //   })
        // ]
      },
      terserOptions: {
        compress: {
          drop_console: true
        }
      }
    },
    server: {
      host: '0.0.0.0',
      https: true,
      proxy: {
        '/api': {
          target: 'https://demo-cloud.appiron.com.cn:37543/',
          changeOrigin: true
        }
      }
    }
  })
}
